import { CacheToken } from "@/constants/cacheKey";
import { IObject, IUserInfo, IUserPermissionsResponse, IMenuInfoResponse } from "@/types/interface";
import { getSysRouteMap } from "@/router";
import baseService from "@/service/baseService";
import { removeCache } from "@/utils/cache";
import { mergeServerRoute, mergeStaticAndDynamicRoutes } from "@/utils/router";
import { MenuStateManager } from "@/utils/menuState";
import { defineStore } from "pinia";
import { permissionApi } from "@/api/authority";
import baseRoutes from "@/router/base";
import { accountSelfApi } from "@/api/business";
import { filterMenus } from "@/utils/menuFilter";
import { logger } from "@/utils/logger";

export const useAppStore = defineStore("useAppStore", {
  state: () => ({
    state: {
      appIsLogin: false, //是否登录
      appIsReady: false, //app数据是否就绪
      appIsRender: false, //app是否开始渲染内容
      permissions: [], //权限集合
      user: {
        createDate: "",
        deptId: "",
        deptName: "",
        email: "",
        gender: 0,
        headUrl: "",
        id: "",
        mobile: "",
        postIdList: "",
        realName: "",
        roleIdList: "",
        status: 0,
        superAdmin: 0,
        username: ""
      }, //用户信息
      dicts: [], //字典
      routes: [], //最终的路由集合
      menus: [], //菜单集合
      routeToMeta: {}, //url对应标题meta信息
      tabs: [], //tab标签页集合
      activeTabName: "", //tab当前焦点页
      closedTabs: [], //存储已经关闭过的tab
      staticRoutes: [], //静态路由（base.ts中定义的路由）
      dynamicRoutes: [] //动态路由（从后端获取的路由）
    } as IObject
  }),
  actions: {
    updateState(data: IObject) {
      Object.keys(data).forEach((x: string) => {
        this.state[x] = data[x];
      });
    },
    initApp() {
      return Promise.all([
        permissionApi.getMenuInfo(), // 获取菜单信息
        permissionApi.getUserPermissions(), // 获取用户权限
        accountSelfApi.getInfo(), // 加载用户信息
        // baseService.get("sys/user/info"), // 加载用户信息
        baseService.get("/sys/dict/type/all") // 加载字典
      ]).then(([menuResponse, permissionResponse, user, dicts]) => {
        if (user.code !== 0) {
          logger.error("初始化用户数据错误", user.msg);
        }

        // 处理菜单数据（恢复为：静态 + 动态 合并）
        let menuData = menuResponse.data || [];
        
        // 应用菜单过滤
        menuData = filterMenus(menuData);


        const [dynamicRoutes, routeToMeta] = mergeServerRoute(menuData, getSysRouteMap());

        // =============== 修改动态路由的映射地址 =======
        const bmsRoute = dynamicRoutes.find((x: any) => x.path === "/iframe/1955508832631681025")!;
        if (bmsRoute && bmsRoute.children) {
          bmsRoute.children.forEach((x: any) => {
            // 确保路径匹配正确
            const path = x.path;
            if (path.includes("early-warning")) {
              x.component = () => import("@/views/bms-monitoring/early-warning/index.vue");
              // x.children = [
              //   {
              //     path: "/warning-detail/:id",
              //     name: "EarlyWarningDetail",
              //     component: () =>
              //       import(
              //         "@/views/bms-monitoring/early-warning/components/EarlyWarningDetail.vue"
              //       ),
              //     meta: {
              //       title: "Warning Details",
              //       showParent: true,
              //       showLink: false
              //     }
              //   }
              // ];
            } else if (path.includes("fault")) {
              x.component = () => import("@/views/bms-monitoring/bms-fault/index.vue");
              // x.children = [
              //   {
              //     path: "/fault-detail/:id",
              //     name: "BMSFaultDetail",
              //     component: () =>
              //       import("@/views/bms-monitoring/bms-fault/components/BMSFaultDetail.vue"),
              //     meta: {
              //       title: "Fault Details",
              //       showParent: true,
              //       showLink: false
              //     }
              //   }
              // ];
            } else {
              x.component = () =>
                import("@/views/bms-monitoring/battery-pack-monitoring/index.vue");
              // x.children = [
              //   {
              //     path: "/battery-detail/:id",
              //     name: "BatteryDetail",
              //     component: () =>
              //       import(
              //         "@/views/bms-monitoring/battery-pack-monitoring/components/BatteryPackDetail/index.vue"
              //       ),
              //     meta: {
              //       title: "Battery Detail",
              //       showParent: true,
              //       showLink: false
              //     }
              //   }
              // ];
            }
          });
        }

        logger.debug("dynamicRoutes", dynamicRoutes);

        // debugger;
        const mergedRoutes = mergeStaticAndDynamicRoutes(baseRoutes, dynamicRoutes);

        // 处理权限数据：统一为去重且裁剪后的字符串数组
        const permissions = Array.from(
          new Set(
            (permissionResponse.data || [])
              .map((x: any) => String(x).trim())
              .filter((x: string) => !!x)
          )
        );

        // if (import.meta.env.DEV) {
        //   logger.debug("用户信息获取成功:", user.data);
        //   logger.debug("菜单信息获取成功:", menuData);
        //   logger.debug("权限信息获取成功(规范化后):", permissions);
        //   logger.debug("静态路由:", baseRoutes);
        //   logger.debug("动态路由:", dynamicRoutes);
        //   logger.debug("合并后的路由:", mergedRoutes);
        // }

        this.updateState({
          permissions: permissions,
          user: user.data || {},
          dicts: dicts.data || [],
          routeToMeta: routeToMeta || {},
          menus: menuData,
          routes: mergedRoutes, // 使用合并后的路由
          staticRoutes: baseRoutes, // 保存静态路由
          dynamicRoutes: dynamicRoutes // 保存动态路由
        });
        return mergedRoutes;
      });
    },
    //退出
    logout() {
      removeCache(CacheToken, true);
      // 清除菜单状态缓存
      MenuStateManager.clearMenuState();
      this.updateState({
        appIsLogin: false,
        permissions: [],
        user: {},
        dicts: [],
        menus: [],
        routes: [],
        tabs: [],
        activeTabName: "",
        staticRoutes: [],
        dynamicRoutes: []
      });
    }
  }
});
